//
//  Xhh_loadingView.m
//  RefreshView
//
//  Created by 郭辉 on 14-5-5.
//  Copyright (c) 2014年 com.guohui.app. All rights reserved.
//

#import "Xhh_loadingView.h"

#define kWidth      self.bounds.size.width
#define kHeight     self.bounds.size.height

@implementation Xhh_loadingView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

#pragma mark - setter
- (void)setDrawColor:(UIColor *)drawColor
{
    _drawColor = drawColor;
    [self setNeedsDisplay];
}

- (void)setProgress:(CGFloat)progress
{
    _progress = progress;
    [self setNeedsDisplay];
}

#pragma mark - public method
- (void)startAnimation
{
    CABasicAnimation* rotate =  [CABasicAnimation animationWithKeyPath: @"transform.rotation.z"];
    rotate.removedOnCompletion = FALSE;
    rotate.fillMode = kCAFillModeForwards;
    
    //Do a series of 5 quarter turns for a total of a 1.25 turns
    //(2PI is a full turn, so pi/2 is a quarter turn)
    [rotate setToValue: [NSNumber numberWithFloat: M_PI / 2]];
    rotate.repeatCount = INTMAX_MAX;
    
    rotate.duration = 0.2;
    //            rotate.beginTime = start;
    rotate.cumulative = TRUE;
    rotate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    
    [self.layer addAnimation:rotate forKey:@"rotateLoadingView"];
}

- (void)stopAnimation
{
    [self.layer removeAnimationForKey:@"rotateLoadingView"];
}

#pragma mark - draw rect
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGContextSetLineWidth(ctx, 1.f);
    CGContextSetLineCap(ctx, kCGLineCapRound);
    CGContextSetStrokeColorWithColor(ctx, self.drawColor.CGColor);
    CGFloat startAngle = - M_PI / 3;
    CGFloat step = 11 * M_PI / 6 * self.progress;
    CGContextAddArc(ctx, kWidth / 2, kHeight / 2, kWidth / 2 - 3, startAngle, startAngle + step, 0);
    CGContextStrokePath(ctx);
}

@end
